﻿using System;
using System.Collections.Generic;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using Abp.Timing;
using Abp.UI;
using Microsoft.EntityFrameworkCore;
using StockSystem.StockSystem.InStocks.Dtos;
using StockSystem.StockSystem.OutStocks.Dtos;
using StockSystem.StockSystem.Stockings;

namespace StockSystem.StockSystem.OutStocks
{
    public class OutStockSummaryAppService : StockSystemAppServiceBase, IOutStockSummaryAppService
    {
        private readonly IRepository<OutStockSummary> _outStockSummaryRepository;
        private readonly IRepository<Stocking> _stockingRepository;

        public OutStockSummaryAppService(IRepository<OutStockSummary> outStockSummaryRepository,
            IRepository<Stocking> stockingRepository)
        {
            _outStockSummaryRepository = outStockSummaryRepository;
            this._stockingRepository = stockingRepository;
        }

        public async Task DoOutStockAsync(CreateOrUpdateOutStockInput input)
        {
            var outStockSummaryEditDto = input.OutStockSummaryEditDto;

            //判断出库单号是否存在
            var o1 = await _outStockSummaryRepository.FirstOrDefaultAsync(x => x.OutStockCode == outStockSummaryEditDto.OutStockCode);
            if (o1 != null)
            {
                throw new UserFriendlyException("您输入的单号已经存在，请重新输入！");
            }
            //计算金额
            Decimal totalAmount = 0;//订单总金额
            
            outStockSummaryEditDto.OutStockDetails.ForEach(e=> {
                e.OutStockSumPrice = e.OutStockPrice * e.OutStockAmount;//计算每条小条目的总金额
                totalAmount += e.OutStockSumPrice;//累加求总金额
                //判断每件物品是否库存充足
                var stocking = _stockingRepository.FirstOrDefault(x => x.GoodsId == e.GoodsId);
                if (stocking == null)
                {
                    throw new UserFriendlyException("您选择的出库货物没有库存，请重试！");
                }
                else if(stocking.StockingNumber < e.OutStockAmount)
                {
                    throw new UserFriendlyException("您选择的出库货物大于您的库存，请重试！");
                }
                else
                {
                    //更新库存
                    stocking.StockingNumber -= e.OutStockAmount;
                    _stockingRepository.Update(stocking);
                }
            });
            outStockSummaryEditDto.TotalAmount = totalAmount;//写入总金额

            //auto maper
            var entity = outStockSummaryEditDto.MapTo<OutStockSummary>();
            entity.OperatingTime = Clock.Now;
            //保存summary
            await _outStockSummaryRepository.InsertAsync(entity);

        }

        public async Task<OutStockSummaryListDto> GetOutstockSummaryByIdAsync(NullableIdDto<int> input)
        {
            var entity = await _outStockSummaryRepository.GetAsync(input.Id.Value);
            var dto = entity.MapTo<OutStockSummaryListDto>();
            dto.CustomerName = dto.Customer.CustomerName;
            return dto;
        }

        public async Task<PagedResultDto<OutStockSummaryListDto>> GetPagedOutStockSummaryAsync(GetOutStockSummaryInput input)
        {
            var query = _outStockSummaryRepository.GetAllIncluding(x => x.Customer);
            var outStockSummariesCount = await query.CountAsync();
            var outStockSummaries = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();
            var dtos = outStockSummaries.MapTo<List<OutStockSummaryListDto>>();
            dtos.ForEach(x => {
                if (x.Customer != null)
                {
                    x.CustomerName = x.Customer.CustomerName;
                }
            });
            return new PagedResultDto<OutStockSummaryListDto>(outStockSummariesCount, dtos);
        }
    }
}
